﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using Rison.DBHelper;
using System.Data.SqlClient;

namespace Rison.DataAccess.Common
{
    public abstract class DataAccessBase : DbBaseHelper, IDataAccess
    {
        //save 或 update 的sql参数集合
        private List<SqlParameter> _sqlParams = null;

        public DataAccessBase()
            : base()
        {
        }

        public DataAccessBase(DbBaseHelper dbTransaction)
            : base(dbTransaction)
        {
        }
        

        //数据表名称
        protected abstract string tableName { get; }

        //自增长列字段的名称
        protected virtual string IdentityFieldName
        {
            get { return "ID"; }
        }

        /// <summary>
        /// 主键字段名称。（字符类型）
        /// 与IdentityFieldName必须至少指定一个，用于默认的Retrieve和Delete。
        /// Retrieve和Delete时，系统默认下不支持联合主键，若需要使用联合主键，需自行特别实现。
        /// </summary>
        protected virtual string KeyFieldName
        {
            get { return string.Empty; }
        }

        //排序字段
        protected virtual string OrderBy
        {
            get { return string.Empty; }
        }

        #region "  save  "
        public virtual long Save(List<SqlField> fields)
        {
            try
            {
                return base.ExecuteNonSqlIdentity(SqlFieldConverter.TurnToInsertSqlString(fields, tableName, ref _sqlParams), _sqlParams);
            }
            catch { throw; }
        }
        #endregion


        protected virtual StringBuilder GetRetrieveSqlString()
        {
            return null; 
        }


        #region "  retrieve  "
        public virtual DataRow Retrieve(int identityValue)
        {
            return Retrieve(identityValue.ToString(), true);
        }

        public virtual DataRow Retrieve(long identityValue)
        {
            return Retrieve(identityValue.ToString(), true);
        }

        public virtual DataRow Retrieve(string keyValue)
        {
            return Retrieve(keyValue, false);
        }

        /// <summary>
        /// 读取实体对象的数据行
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="isNumber">关键字字段是否是数值型。</param>
        /// <returns></returns>
        public virtual DataRow Retrieve(string keyValue, bool isNumber)
        {
            return Retrieve(string.Empty, keyValue, isNumber);
        }

        public virtual DataRow Retrieve(string keyName, string keyValue)
        {
            return Retrieve(keyName, keyValue, false);
        }

        public virtual DataRow Retrieve(string keyName, string keyValue, bool isNumber)
        {
            StringBuilder sql = GetRetrieveSqlString();
            if (sql == null)
            {
                sql = new StringBuilder();
                sql.AppendFormat("select * from {0}", tableName);
            }

            sql.AppendFormat(" where {0}.", tableName);
            if (string.IsNullOrEmpty(keyName))
                sql.Append(string.IsNullOrEmpty(KeyFieldName) ? IdentityFieldName : KeyFieldName);
            else
                sql.Append(keyName);

            if (isNumber)
                sql.AppendFormat("={0}", keyValue);
            else
                sql.AppendFormat("='{0}'", keyValue);

            try
            {
                return base.ExecuteSqlToDataRow(sql.ToString());
            }
            catch { throw; }
            finally { sql = null; }
        }

        public virtual DataRow Retrieve(List<SqlField> fields)
        {
            try
            {
                return base.ExecuteSqlToDataRow(SqlFieldConverter.TurnToRetrieveSqlString(fields, tableName));
            }
            catch { throw; }
        }
        #endregion


        #region "  update  "
        public virtual int Update(List<SqlField> fields)
        {
            try
            {
                return base.ExecuteNonSql(SqlFieldConverter.TurnToUpdateSqlString(fields, tableName, ref _sqlParams), _sqlParams);
            }
            catch { throw; }
        }
        #endregion


        #region "  delete  "
        public virtual int Delete(int identityValue)
        {
            return Delete(identityValue.ToString(), true);
        }

        public virtual int Delete(long identityValue)
        {
            return Delete(identityValue.ToString(), true);
        }

        public virtual int Delete(string keyValue)
        {
            return Delete(keyValue, false);
        }

        /// <summary>
        /// 删除一行数据。
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="isNumber">关键字字段是否是数值型。</param>
        /// <returns></returns>
        public virtual int Delete(string keyValue, bool isNumber)
        {
            StringBuilder sql = new StringBuilder();
            if (isNumber)
                sql.AppendFormat("delete from {0} where {1}={2}", tableName, string.IsNullOrEmpty(KeyFieldName) ? IdentityFieldName : KeyFieldName, keyValue);
            else
                sql.AppendFormat("delete from {0} where {1}='{2}'", tableName, string.IsNullOrEmpty(KeyFieldName) ? IdentityFieldName : KeyFieldName, keyValue);

            try
            {
                return base.ExecuteNonSql(sql.ToString());
            }
            catch { throw; }
        }
        #endregion


        protected virtual string GetSqlFromTable()
        {
            return "select * from " + tableName;
        }

        protected virtual string GetSqlString(string strCondtion)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(GetSqlFromTable());

            if(!string .IsNullOrEmpty (strCondtion))
                sql.AppendFormat(" where {0}", strCondtion);

            if (!string.IsNullOrEmpty(OrderBy))
                sql.AppendFormat(" order by {0}", OrderBy);

            return sql.ToString();
        }


        public virtual DataSet GetAllData()
        {
            try
            {
                return base.ExecuteSql(GetSqlString(string.Empty), "GetAllData");
            }
            catch { throw; }
        }

        public virtual DataSet GetDataBy(string strCondtion)
        {
            try
            {
                return base.ExecuteSql(GetSqlString(strCondtion), "GetDataBy");
            }
            catch { throw; }
        }

    

    }
}
